
package com.weiqiao.mall.service.impl;

import com.google.gson.Gson;
import com.mingsoft.util.PageUtil;
import com.mingsoft.util.StringUtil;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import com.weiqiao.mall.domain.ShopkeeperEntity;
import com.weiqiao.mall.repository.IShopkeeperRepository;
import com.weiqiao.mall.service.IShopkeeperService;
import com.weiqiao.mall.service.mapper.AddressMapper;
import com.weiqiao.mall.service.vo.AddressVO;
import com.weiqiao.utils.RedisUtil;
import com.weiqiao.utils.WeiXinUtils;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 微信小程序商城 配置 业务层实现类，继承BaseWeiXinBizImpl，实现IShopkeeperBiz
 *
 * @author tiyer
 */
@Service("ShopkeeperServiceImpl")
public class ShopkeeperServiceImpl extends BaseWeiXinServiceImpl implements IShopkeeperService {

    /**
     * 注入商铺管理持久化层
     */
    @Autowired
    @Qualifier("ShopkeeperRepositoryImpl")
    private IShopkeeperRepository shopkeeperDao;

    @Autowired
    private AddressMapper addressMapper;

    /**
     * 转换时间戳为时间字符串
     */
    public String formateTime(String dateStr) {
        try {
            if (StringUtil.isLong(dateStr)) {
                String date = WeiXinUtils.format(new Date(Long.parseLong(dateStr)), "yyyy-MM-dd HH:mm");
                dateStr = date;
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return dateStr;
    }

    public List<ShopkeeperEntity> findShopByBsonPage(int company_id, Bson bson, PageUtil page) {
        // 计算页码
        int pageSize = page.getPageSize();
        int skip = pageSize * page.getPageNo();
        // 排序
        Bson sort = Filters.eq("mall_id", 1);
        Gson gson = new Gson();
        List<ShopkeeperEntity> shop = new ArrayList<ShopkeeperEntity>();
        List<String> list = shopkeeperDao.getShopsByFilterSortSkipLimt(company_id, bson, sort, skip, pageSize);
        if (!list.isEmpty()) {
            for (String a : list) {
                ShopkeeperEntity s = gson.fromJson(a, ShopkeeperEntity.class);
                s.setCreatedate(this.formateTime(s.getCreatedate()));
                shop.add(s);
            }
        }
        return shop;
    }

    @Override
    public ShopkeeperEntity getOneShop(Bson filter) {
        String inf = shopkeeperDao.getOne(filter);
        ShopkeeperEntity shop = new ShopkeeperEntity();
        if (!StringUtils.isBlank(inf)) {
            shop = new Gson().fromJson(inf, ShopkeeperEntity.class);
        }
        return shop;
    }

    /**
     * 获取最新的一条服务,并且是在App端显示未删除的一条服务
     */
    public ShopkeeperEntity.ReservationService getTopOneServices(int company_id, String article_id) {
        Bson bson = Filters.eq("company_id", company_id);
        String str = shopkeeperDao.getOne(bson);
        if (StringUtils.isBlank(str)) {
            return null;
        }
        ShopkeeperEntity shop = new Gson().fromJson(str, ShopkeeperEntity.class);
        List<ShopkeeperEntity.ReservationService> list = shop.getServiceText();
        if (list == null || list.size() == 0) {
            return null;
        }
        // 如果服务id为空 就按照条件查询 否则就根据服务id查询
        if (StringUtils.isBlank(article_id)) {
            list = list.stream().filter(s -> (s.getState() == 1 && s.getIs_delete() == 0)).collect(Collectors.toList());
            list.sort(Comparator.comparing(ShopkeeperEntity.ReservationService::getCreate_date).reversed());
        } else {
            ShopkeeperEntity.ReservationService entity = null;
            for (ShopkeeperEntity.ReservationService s : list) {
                if (article_id.equalsIgnoreCase(s.getArticle_id())) {
                    entity = s;
                    break;
                }
            }
            return entity;
        }
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    private Document shopTopicTitleDoc() {
        Document docP = new Document();
        docP.append("$project",
                new Document("shop_topic_title_unwind", "$shop_topic_title.shop_topic_title_unwind")
                        .append("title_id", "$shop_topic_title.title_id").append("title_content", "$shop_topic_title.title_content")
                        .append("topic_ids", "$shop_topic_title.topic_ids").append("visit_num", "$shop_topic_title.visit_num")
                        .append("editor", "$shop_topic_title.editor").append("create_date", "$shop_topic_title.create_date")
                        .append("status", "$shop_topic_title.status").append("cover_img", "$shop_topic_title.cover_img")
                        .append("topic_type", "$shop_topic_title.topic_type")
        );
        return docP;
    }

    private Document shopTopicDoc() {
        Document docP = new Document();
        docP.append("$project",
                new Document("shop_topic_unwind", "$shop_topic.shop_topic_unwind")
                        .append("topic_id", "$shop_topic.topic_id").append("topic_name", "$shop_topic.topic_name")
                        .append("topic_content", "$shop_topic.topic_content").append("commodity_id", "$shop_topic.commodity_id")
                        .append("weight", "$shop_topic.weight").append("create_date", "$shop_topic.create_date"));
        return docP;
    }

    @Override
    public boolean updateShopByEntity(ShopkeeperEntity entity) {
        if (StringUtil.isBlank(entity)) {
            return false;
        }
        String str = new Gson().toJson(entity);
        Document doc = Document.parse(str);
        Document document = new Document();
        document.append("company_id", entity.getCompany_id());
        //将返利生效公司ID添加到Redis
        if (!StringUtil.isBlank(doc.get("rebate_company_id"))) {
            Jedis jedis = RedisUtil.getJedis();
            try {
                String rebate_company_id = doc.get("rebate_company_id") + "";
                jedis.set("rebate_company_id", rebate_company_id);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                RedisUtil.returnResource(jedis);
            }
        }
        return shopkeeperDao.updateShop(document, doc);
    }

    @Override
    public boolean updateShopByBson(Bson filter, Bson bson) {
        boolean result = shopkeeperDao.updateShopByBson(filter, bson);
        return result;
    }

    @Override
    public boolean updateShopByJson(Bson filter, String json) {

        return shopkeeperDao.updateShop(filter, json);
    }

    @Override
    public boolean updateAddress(AddressVO address) {
        boolean result = false;
        Document document = new Document();
        document.append("company_id", address.getCompany_id());
        // 根据number 地址编号是否为空来判断是新建 还是更新
        if (StringUtil.isBlank(address.getNumber())) {
            ShopkeeperEntity.AddressManagement addressManagement = addressMapper.toDto(address);
            // 地址编号
            addressManagement.setNumber(String.valueOf(System.currentTimeMillis()));
            // 地址状态  1没有删除  0删除  新建的时候为没有删除状态
            addressManagement.setIs_remove(1);
            Bson bson = Updates.push("address_setting", Document.parse(new Gson().toJson(addressManagement)));
            result = updateShopByBson(document, bson);
        } else {
            // 查找出商城配置 里面有地址管理
            ShopkeeperEntity shop = getOneShop(document);
            for (int i = 0; i < shop.getAddress_setting().size(); i++) {
                if (address.getNumber().equals(shop.getAddress_setting().get(i).getNumber())) {
                    // 市
                    shop.getAddress_setting().get(i).setCity(address.getCity());
                    // 联系人
                    shop.getAddress_setting().get(i).setContacts(address.getContacts());
                    // 座机号 类似123-123-123 的拼接
                    shop.getAddress_setting().get(i).setLandline_telephone(address.getLandline_telephone());
                    // 省
                    shop.getAddress_setting().get(i).setProvince(address.getProvince());
                    // 详细地址
                    shop.getAddress_setting().get(i).setStreet(address.getStreet());
                    // 联系电话
                    shop.getAddress_setting().get(i).setTel(address.getTel());
                    // 地址类型
                    shop.getAddress_setting().get(i).setType(address.getType());
                    break;
                }
            }
            // 更新预约服务文本
            result = updateShopByJson(document, new Gson().toJson(shop));
        }
        return result;
    }

    @Override
    public boolean deleteAddress(AddressVO address) {
        Document document = new Document();
        document.append("company_id", address.getCompany_id());
        // 获取商城配置
        ShopkeeperEntity shop = getOneShop(document);
        if (StringUtil.isBlank(shop)) {
            return false;
        }
        // 查找出对应的地址 进行设置为删除状态
        for (int i = 0; i < shop.getAddress_setting().size(); i++) {
            if (address.getNumber().equals(shop.getAddress_setting().get(i).getNumber())) {
                shop.getAddress_setting().get(i).setIs_remove(0);
                break;
            }
        }
        return updateShopByJson(document, new Gson().toJson(shop));
    }

    @Override
    public Map getMallList(AddressVO address) {
        Map map = new HashMap<>();
        Document document = new Document();
        document.append("company_id", address.getCompany_id());
        // 获取店铺信息
        ShopkeeperEntity shop = this.getOneShop(document);
        // 如果没有则默认新建
        if (StringUtil.isBlank(shop.getCompany_id()) || shop.getCompany_id() == 0) {
            shop.setCompany_id(address.getCompany_id());
            String shopkeeper = new Gson().toJson(shop);
            shopkeeperDao.updateShop(document, Document.parse(shopkeeper));
        }
        map.put("result", true);
        map.put("shop", shop);
        return map;
    }
}
